<?php
/**
 * 商品管理控制器
 */
class GoodsController extends AuthController{
    private $model;
    /**
     * 自动运行
     */
    public function __init(){
        parent::__init();
        $this->model = K('Goods');
    }
    /**
     * 商品列表
     */
    public function index(){
        // 获得所有商品数据
        $g_data = $this->model->all();
        // 循环获得所对应商品gid的库存数组
        foreach ($g_data as $k=>$v) {
            $inventory = M('goods_list')->where(array('goods_gid' => $v['gid']))->getField('inventory',true);
            // p($inventory);
            $sum = 0;
            // 循环库存数组，把该商品的货品库存循环相加后赋给设置好的变量$sum
            foreach ($inventory as $v) {
                $sum += $v;
            }
            // 将该商品的货品库存总和压入到要分配的数组
            $g_data[$k]['sum'] = $sum;
        }
        // p($g_data);
        $this->assign('g_data',$g_data);
        $this->display();
    } 
    /**
     *  添加商品
     */
    public function add_goods(){
    	 // p(Q('post.'));
        if (IS_POST) {
            // p(Q("post."));die;
            // p($this->model->m_add_goods());
            if (!$this->model->m_add_goods()) $this->error($this->model->error);
            $this->success('添加商品成功',U('index'),0.5);
        }
        //选择所属分类
        $c_data = M('category')->order('sort')->all();
        $c_data = Data::tree($c_data,'cname');
        $this->assign('c_data',$c_data);

        // 选择所属品牌
        $b_data = M('brand')->order('sort')->all();
        $this->assign('b_data',$b_data);
    	$this->display();
    }
    /**
     * 通过cid异步获取类型属性
     */
    public function getTypeAttr(){ 
        if (!IS_AJAX) {
            return;
        } 
        $tid = Q('post.tid',0,'intval');
        $ta_data = M('type_attr')->where("type_tid='{$tid}'")->all();
        // p($ta_data);
        foreach ($ta_data as $key => $value) {
            $ta_data[$key]['tavalue'] = explode(',',$value['tavalue']);
        }
        // p($ta_data);
        if ($ta_data === null) {
            echo 0;
        }else{ 
            $this->ajax($ta_data);
            //或者 echo json_encode($data);exit;
        } 
    }

    /**
     * uploadify上传列表图
     */
    public function upload(){
        $upload = new Upload('Upload/goods/' . date('y_m'));
        $file = $upload->upload();
        if (empty($file)) {
                //相当于 echo json_encode('上传失败');exit;
            $this->ajax('上传失败');
        } else {
            $data = $file[0];
            $this->ajax($data);
        }
    }

    /**
     * 商品图册上传
     */
    public function uploadPhoto(){
        $upload = new Upload('Upload/Photo/' . date('y_m'));
        $file = $upload->upload();
        if (empty($file)) {
                //相当于 echo json_encode('上传失败');exit;
            $this->ajax('上传失败');
        } else {
            $data = $file[0];
            $this->ajax($data);
        }
    }
    /**
     *  编辑商品
     */
    public function edit_goods(){
        if (IS_POST) {
            // p(Q('post.'));die;
            // $this->model->m_edit_goods();
            if (!$this->model->m_edit_goods()) $this->error($this->model->error);
            $this->success('编辑成功',U('index'),0.5);
        } 
        // 获得旧数据
        $gid = Q('get.gid',0,'intval');
        // 关联goods表和goods_attr*******************************************
        $join = 'goods g JOIN goods_detail gd ON g.gid=gd.goods_gid';
        $old_data = M()->join($join)->where("gid='{$gid}'")->find(); 
        $old_data['medium'] = explode(',',$old_data['medium']);  
        // p($old_data);
        $this->assign('old_data',$old_data); 
        // 处理所属分类******************************************************
        $c_data = Data::tree(K('Category')->all(),'cname');
        // p($c_data);
        $this->assign('c_data',$c_data);
        // 处理所属品牌******************************************************
        $b_data = K('Brand')->all();
        $this->assign('b_data',$b_data);
        // 处理属性 ****************************************************** 
        $tid = $old_data['type_tid'];   
        // 得到type_tid对应的属性数组
        $ta_data = K('TypeAttr')->where(array('type_tid'=>$tid))->all();
        // 把tavalue组成数组
        foreach ($ta_data as $key => $value) {
            $ta_data[$key]['tavalue'] = explode(',',$value['tavalue']);
        }
        // p($ta_data);
        // 获得不可选的属性数组
        foreach ($ta_data as $value) { 
            if ($value['class']==0) {
                $attr_data[] = array(
                    'taid' => $value['taid'],
                    'taname' => $value['taname'],
                    'tavalue' => $value['tavalue']
                    ); 
            }  
        }
        // p($attr_data);
        // 获得不可选的属性taid
        foreach ($attr_data as $attr) {
            $taid_data[] = $attr['taid'];
        }
        // p($taid_data);
        // 获得商品属性值gavalue
        foreach ($taid_data as $taid) {
            $gavalue_data[] = k('GoodsAttr')->where("type_attr_taid='{$taid}' AND goods_gid='{$gid}'")->getField('gavalue',true);
        }  
        // p($gavalue_data);
        foreach ($gavalue_data as $gavalue) {
            $gav_data[] = isset($gavalue[0])?$gavalue[0]:'';
        } 
        // p($gav_data);DIE;
        // 分配选择属性值数组
        $this->assign('gav_data',$gav_data);   
        $this->assign('attr_data',$attr_data);  
        // 得到规格及附加值
        foreach ($ta_data as $value) {
            if ($value['class']==1&&$value['taname']=='尺码') {
                $spec_s_data = array( 
                    'taid' => $value['taid'],
                    'taname' => $value['taname'],
                    'tavalue' => $value['tavalue']
                    );
            } 
            if ($value['class']==1&&$value['taname']=='颜色') {
                $spec_c_data = array( 
                    'taid' => $value['taid'],
                    'taname' => $value['taname'], 
                    );
            }  
        }
        // p($spec_s_data);
        $this->assign('spec_s_data',$spec_s_data); 
        $spec_s_taid = $spec_s_data['taid']; 
        // p($spec_s_taid); 
        $spec_c_taid = $spec_c_data['taid']; 
        // 获得商品的尺寸及价格数组========================================= 
        $this->assign('spec_s_taid',$spec_s_taid);
        $s_p_date = k('GoodsAttr')->where("type_attr_taid='{$spec_s_taid}' AND goods_gid='{$gid}'")->getField('gavalue,add_price',true);
        // p($s_p_date);
        // 重组尺寸及价格数组
        foreach ($s_p_date as $size => $price) {
            $new_s_p_date[] = array(
                'size'=>$size,
                'price'=>$price
                );
        }
        // p($new_s_p_date);
        $this->assign('new_s_p_date',$new_s_p_date);   
        // 获得商品的颜色及价格数组=========================================
        // p($spec_c_taid);
        $this->assign('spec_c_taid',$spec_c_taid);  
        $c_p_date = k('GoodsAttr')->where("type_attr_taid='{$spec_c_taid}' AND goods_gid='{$gid}'")->getField('gavalue,add_price',true);
        // p($c_p_date);
        // 重组颜色及价格数组
        foreach ($c_p_date as $color => $price) {
            $new_c_p_date[] = array(
                'color'=>$color,
                'price'=>$price
                );
        }
        // p($new_c_p_date);
        $this->assign('new_c_p_date',$new_c_p_date);   
        $this->display(); 
    } 
    /**
     *  删除商品
     */
    public function del_goods(){
        // p(Q('get.gid')); 
        if (IS_AJAX) {
            $url_m = Q('post.url');
            // p($url_m);
            unlink($url_m);
            if(substr($url_m, -10,-4)=='medium'){
                $url = str_replace('_medium', '', $url_m);
                $url_s = str_replace('_medium', '_small', $url_m);
                $url_b = str_replace('_medium', '_big', $url_m); 

                unlink($url);unlink($url_s);unlink($url_b);

            } 
        } 
        // 获得gid
        $gid = Q('get.gid',0,'intval'); 
        // 获得列表图片的地址并删除图片
        $pic_data = $this->model->where("gid='{$gid}'")->getField('pic',true);
        if (isset($pic_data[0])?$pic_data[0]:'') {
           unlink($pic_data[0]);
        } 
        $this->model->where("gid='{$gid}'")->delete(); 
        $where = "goods_gid='{$gid}'"; 
        // 删除商品属性表
        K('GoodsAttr')->where($where)->delete();
        $gd_data = K('GoodsDetail')->where($where)->find(); 
        // p($gd_data);die; 
        // 获得缩略图数组
        $gd_s = explode(',',$gd_data['small']); 
        $gd_m = explode(',',$gd_data['medium']);
        $gd_b = explode(',',$gd_data['big']);   
        // 获得上传本身图片
        foreach ($gd_s as $value) {
            $gd_photo[] = str_replace('_small', '', $value);    
        } 
        // p($gd_photo);die;
        // 合并要删除的图册数组并依次删除
        foreach (array_merge($gd_s,$gd_m,$gd_b,$gd_photo) as $k => $v) {
            if (file_exists($v)) {
                unlink($v);
            }    
        }    
        // 删除商品详细表
        K('GoodsDetail')->where($where)->delete();
        // 删除该商品的所有货品
        K('GoodsList')->where($where)->delete();
        $this->success('删除成功',U('index'),0.5);
    } 


} 